package tests;

import jBittorrentAPI.Constants;
import jBittorrentAPI.DownloadManager;
import jBittorrentAPI.TorrentFile;
import jBittorrentAPI.TorrentProcessor;
import jBittorrentAPI.Utils;

import java.io.File;

public class Peer {
	public static String peername;
	private static int minPort, maxPort, strategy;
	
	private static long upSleep = 0;
	private static long downSleep = 0;
	
	public Peer(String peername, String torrent, int minPort, int maxPort, long upSleep, long downSleep){
		Peer.peername = peername;
		Peer.minPort = minPort;
		Peer.maxPort = maxPort;
		
		Peer.upSleep = upSleep;
		Peer.downSleep = downSleep;
		
		File downloadFolder = new File("downloads/"+peername);
		if(!downloadFolder.exists()){
			downloadFolder.mkdirs();
		}
		leech(peername, torrent, downloadFolder);
	}

	public void leech(String peername, String torrent, File downloadFolder){
		try{
			TorrentProcessor tp = new TorrentProcessor();
			TorrentFile t = tp.getTorrentFile(tp.parseTorrent(torrent));
			Constants.SAVEPATH = downloadFolder.getAbsolutePath()+"/";
			if(t != null) {
				DownloadManager dm = new DownloadManager(t, Utils.generateID(), strategy);
				dm.startListening(minPort, maxPort);
				dm.startTrackerUpdate();
				dm.blockUntilCompletion();
				dm.stopTrackerUpdate();
				dm.closeTempFiles();
			} else {
				System.err.println("Provided file is not a valid torrent file");
				System.err.flush();
				System.exit(1);
			}
		} catch (Exception e) {
			System.out.println("Error while processing torrent file. Please restart the client");
			//e.printStackTrace();
			System.exit(1);
		}
	}

	public static void main(String[] args) {
		// peername .torrent minPort maxPort
		if(args.length != 7 || !args[1].endsWith(".torrent")){
			System.err.println("Incorrect use, please provide a peer name with the path of the torrent file and a port range...\r\n" +
							   "Example: Peer [PeerName] [TorrentPath] [MinPort] [MaxPort] [UpSleep] [DownSleep] [Strategy]");
			System.exit(1);
		}

		peername = args[0];
		String torrent = args[1];
		try{
			minPort = Integer.parseInt(args[2]);
			maxPort = Integer.parseInt(args[3]);
			
			upSleep = Long.parseLong(args[4]);
			downSleep = Long.parseLong(args[5]);
			
			strategy = Integer.parseInt(args[6]);
		} catch (NumberFormatException e) {
			System.err.println("[MinPort], [MaxPort], [UpSleep], [DownSleep] and [Strategy] must be a valid integer value");	
			System.exit(1);
		}

		new Peer(peername, torrent, minPort, maxPort, upSleep, downSleep);
	}
	
	public static String getPeer() {
		return peername; 
	}
	
	public static long getUpSleep() {
		return upSleep;
	}
	
	public static long getDownSleep() {
		return downSleep;
	}
	
	
}
